# -*- coding: utf-8 -*-
import math
import json
from pyquery import PyQuery
from zc_core.model.items import *
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.sku_id_parser import convert_id2code
from zc_core.util.encrypt_util import md5
from epec.matcher import *
from zc_core.util.common import parse_time, parse_number, parse_int


def parse_catalog(response):
    if not response.text:
        return None
    cats = list()

    docs = PyQuery(response.text)
    cats_1 = docs("div.category_list ul li a")
    cats_2 = docs(".market_cl .category_allbox")
    for index in range(len(cats_1)):
        cat_1 = cats_1[index]
        cat1_name = cat_1.text
        entity1 = build_catalog(cat1_name, 1)
        cats.append(entity1)
        cat1_childs = cats_2[index]
        if cat1_childs:
            cat_list_2 = docs(cat1_childs)(".list_box")
            for cat_2 in cat_list_2.items():
                cat2_name = cat_2("h3 a").text()
                entity2 = build_catalog(cat2_name, 2, entity1['catalogId'])
                cats.append(entity2)
                cats_3 = cat_2("p a").items()
                for cat3 in cats_3:
                    cat3_name = cat3.text()
                    entity3 = build_catalog(cat3_name, 3, entity2['catalogId'])
                    cats.append(entity3)

    return cats


def build_catalog(name, level, parent_id=None):
    entity = Catalog()

    entity['catalogId'] = md5(name + "_" + str(level))
    entity['catalogName'] = name
    entity['parentId'] = parent_id
    entity['level'] = level
    if entity['level'] == 3:
        entity['leafFlag'] = 1
    else:
        entity['leafFlag'] = 0
    entity['linkable'] = 0
    return entity


def parse_sku(response):
    docs = PyQuery(response.text)
    meta = response.meta
    batch_no = meta.get('batchNo')
    catalog3_id = meta.get('catalogId', None)
    catalog3_name = meta.get('catalogName', None)
    kw = meta.get('kw', None)

    cat_helper = CatalogHelper()
    sku_list = list()
    item_list = list()
    skus = docs('.newPage-contents')
    if skus:
        for card in skus.items():
            sku = card(".new_btlist")
            sku_link = sku("h4 a")
            sku_id = match_sku_id(sku_link.attr('href'))
            sku_name = sku_link.text()
            supplier_link = sku("h3 a")
            supplier_name = supplier_link.text()
            supplier_id = match_supplier_id(supplier_link.attr('href'))
            sale_price = ''
            price = sku(".right_box p")
            if price:
                sale_price = match_sale_price(price.text())

            brand_id = ''
            brand_name_sub = ''
            brand_model = ''
            sold_count = 0
            unit = ''
            sku_img = card("a .old_img").attr("src")

            attr = card(".sS-newPage-shadraw p")
            if attr:
                sold_count, unit = match_sale_count(attr.eq(0).text())
                brand_name_sub, brand_model = match_brand(attr.eq(2).text())

            brand_name = card('.new_btlist h4 nobr').text().strip()
            if brand_name != '':
                brand_id = md5(brand_name)
            else:
                brand_name = brand_name_sub
            entity = Sku()
            entity['batchNo'] = batch_no
            entity['skuId'] = sku_id
            # entity['skuCode'] = kw
            entity['supplierId'] = supplier_id
            entity['supplierName'] = supplier_name
            entity['catalog3Id'] = catalog3_id
            entity['catalog3Name'] = catalog3_name
            entity['brandId'] = brand_id
            entity['brandName'] = brand_name
            entity['salePrice'] = parse_number(sale_price)
            sku_list.append(entity)

            item = ItemData()
            item['batchNo'] = batch_no
            item['skuId'] = sku_id
            # item['skuCode'] = kw
            item['skuName'] = sku_name.strip()
            item['originPrice'] = parse_number(sale_price)
            item['salePrice'] = parse_number(sale_price)
            item['skuImg'] = sku_img
            item['supplierId'] = supplier_id
            item['supplierName'] = supplier_name

            item['brandId'] = brand_id
            item['brandModel'] = brand_model
            item['brandName'] = brand_name
            item['catalog3Id'] = catalog3_id
            item['catalog3Name'] = catalog3_name
            item['soldCount'] = int(sold_count)
            item['unit'] = unit

            # if sp_sku_id:
            #     item['supplierSkuId'] = sp_sku_id
            #     plat_code = None
            #     if item['supplierId'] == '143245' or '得力' in item['supplierName']:
            #         plat_code = 'deli'
            #     item['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)

            cat_helper.fill(item)
            if item['salePrice'] != None and item['salePrice'] != -1:
                item_list.append(item)

    return sku_list, item_list


def parse_item_data(response):
    cat_helper = CatalogHelper()
    if not response.text:
        return None
    meta = response.meta
    batch_no = meta.get('batchNo')
    catalog3_id = meta.get('catalog3Id')
    catalog3_name = meta.get('catalog3Name')
    supplier_name = meta.get('supplierName')
    supplier_id = meta.get('supplierId')

    items = list()
    skus_json = json.loads(response.text)
    for sku in skus_json:
        sku_id = str(sku.get("productSkuId"))
        sku_name = sku.get("skuOptionValueInfo")
        sale_price = float(sku.get("memberprice"))
        sku_img = sku.get("imageUrl")
        unit = sku.get("mdmUnitName")

        item = ItemData()
        item['batchNo'] = batch_no
        item['skuId'] = sku_id
        item['skuName'] = sku_name.strip()
        item['originPrice'] = sale_price
        item['salePrice'] = sale_price
        item['skuImg'] = sku_img
        item['supplierId'] = supplier_id
        item['supplierName'] = supplier_name
        item['catalog3Id'] = catalog3_id
        item['catalog3Name'] = catalog3_name
        item['unit'] = unit
        cat_helper.fill(item)
        items.append(item)

    return items


def parse_total_page(response, page_size):
    docs = PyQuery(response.text)
    total_count = match_total_count(response.text)
    if total_count:
        total_page = math.ceil(int(total_count) / page_size)
        return total_page

    return 0
